---
title: ""
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
    - \usepackage{caption}
    - \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, arrow, readr, tidyr, glue, argparse, here, purrr, stringr, dplyr, knitr, kableExtra, stats);

# Working directory and command line argument setup
current_script = "generate_tables_and_figures/gen_outreach_model_outputs/src/gen_outreach_model_outputs.Rmd"
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "OUTREACH_RESULTS",
  "HOURS_WORKED_RESULTS",
  "CONFIG_FILE",
  "OUTCOME_LABELS_FILE",
  "TABLE_CONFIG",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()
  
```


```{r}

config <- read_yaml(cl_args$CONFIG_FILE)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE, show_col_types = F) %>%
  rename(term = value)

table_config <- read_yaml(cl_args$TABLE_CONFIG)
source('../R/table_functions.R')

beta_se_digits <- table_config$digits$beta_se

baseline_vars <- tibble(
  term = c(config$baseline_demos_varlist, 
           config$baseline_outcomes_varlist, 
           config$baseline_uphat_varlist,
           config$baseline_arrests_varlist, 
           config$baseline_vics_varlist,
           config$baseline_incar_varlist,
           config$baseline_nbhood_varlist,
           config$baseline_pathway_varlist)) %>%
  mutate(order = row_number())

add_baseline_group_rows <- function(kable) {
  kable %>%
    group_rows("Demographics", 1, 2) %>%
    group_rows("Primary Outcome Components", 3, 5) %>%
    group_rows("Risk Prediction", 6, 7) %>%
    group_rows("Arrest Counts", 8, 11) %>%
    group_rows("Victimization Counts", 12, 13) %>%
    group_rows("Incarceration Measures", 14, 15) %>%
    group_rows("Neighborhood", 16, 17)
}

```


```{r}

results <- read_csv(cl_args$OUTREACH_RESULTS, show_col_types = F) %>%
  filter(covariate_set == config$covariate_set,
         outcome == config$outcome_set) %>%
  mutate(term = gsub('_pre$', '', term)) %>%
  left_join(baseline_vars, by = 'term') %>%
  left_join(ylabels %>% select(term, label), by = 'term') %>%
  select(-term) %>% rename(term = label) %>%
  # shorten one label
  mutate(term = case_when(term == 'Other (Non-Shooting) Violent Victimizations' ~ "Non-Shooting Violent Victimizations",
                          TRUE ~ term)) %>%
  mutate(term = case_when(term == 'ULRA Risk Score (Zero-Imputed)' ~ "Risk Score (Zero-Imputed)",
                          TRUE ~ term)) %>%
  mutate(term = case_when(term %in% config$non_std_columns ~ term,
                          TRUE ~ paste(term, '(std.)')),
         n = as.character(n),
         beta = fmt(beta, decimals = 3),
         beta = paste0(beta, replace_na(istar, '')),
         adj_r2 = fmt(adj_r2, decimals = 3),
         treatment_mean = fmt(treatment_mean, decimals = 3))

results <- bind_rows(

    results %>%
    select(outcome, order, covariate_set, term, beta),
  
  results %>%
    select(outcome, covariate_set, adj_r2) %>%
    mutate(term = 'Adjusted R-squared', 
           order = 999) %>%
    rename(beta = adj_r2) %>%
    distinct())

table <- results %>%
  arrange(order) %>%
  select(term, beta) %>%
  kable(booktabs = table_config$booktabs, 
        longtable = table_config$longtable,
        col.names = c(" ", 'Outreach Referral'),
        align = c(table_config$alignment$text, 
                  table_config$alignment$numeric),
        linesep = '') %>% 
  kable_styling(font_size = 12) %>%
  add_baseline_group_rows() %>%
  column_spec(1, width="25em", latex_valign = "b") %>%
  column_spec(2:9, width="10em", latex_valign = "b") %>%
  row_spec(nrow(results)-1, hline_after = T)

table

# SAVE

timestamp <- get_timestamp()
writeLines(table, glue(cl_args$OUT_DIR, "/outreach_model_up_to_date.tex"))
writeLines(table, glue(cl_args$OUT_DIR, "/outreach_model_{timestamp}.tex"))

```


